﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Linq.Mapping;
using System.Data;
using System.IO;

namespace Database
{
    public partial class DatabaseDataContext
    {
        //protected internal static string ConnectionString = Artifacts.Helper.getValueFormConfigFile("sqlserver_database");
        protected internal static string ConnectionString = ConfigurationManager.ConnectionStrings["QuaackSqlConnection"].ConnectionString;
        protected internal static System.Data.Linq.Mapping.MappingSource mappingSourceCached = null;

        /// <summary>
        /// Get the database context object
        /// </summary>
        /// <returns></returns>
        public static DatabaseDataContext Database()
        {
            DatabaseDataContext db = null;
            if (mappingSourceCached == null)
            {
                db = new DatabaseDataContext(ConnectionString);
                mappingSourceCached = db.Mapping.MappingSource;
                return db;
            }

            db = new DatabaseDataContext(ConnectionString, mappingSourceCached);



#if DEBUG
            db.Log = new DebugTextWriter();
#endif
            return db;
        }

        class DebugTextWriter : System.IO.TextWriter
        {
            public override void Write(char[] buffer, int index, int count)
            {
                System.Diagnostics.Debug.Write(new String(buffer, index, count));
            }

            public override void Write(string value)
            {
                System.Diagnostics.Debug.Write(value);
            }

            public override Encoding Encoding
            {
                get { return System.Text.Encoding.Default; }
            }
        }
    }
}
